/**
 * Created by frank on 2016/8/31.
 */
(function () {
    'use strict';

    angular
        .module('home.controller', [])
        .controller('HomeCtrl', HomeCtrl)
        .directive('repeatFinish', function () {
            return {
                link: function (scope, element, attr) {
                    if (scope.$last == true) {
                        scope.$eval(attr.repeatFinish);
                    }
                }
            }
        });

    HomeCtrl.$inject = ['$scope', '$yikeUtils', '$rootScope', '$ionicModal', '$state', '$ionicHistory', '$ionicTabsDelegate', 'localStorageService', '$ionicPopup', '$ionicSlideBoxDelegate', '$ionicLoading', '$sce', '$ionicPlatform'];
    /* @ngInject */
    function HomeCtrl($scope, $yikeUtils, $rootScope, $ionicModal, $state, $ionicHistory, $ionicTabsDelegate, localStorageService, $ionicPopup, $ionicSlideBoxDelegate, $ionicLoading, $sce, $ionicPlatform) {
        $scope.$on('$ionicView.enter', function () {
            $rootScope.hideTabs = true;
        });
        $scope.leftStatus = 0;
        //新闻专状态值
        $scope.activeStatu = '';

        $scope.leftActive = leftActive;
        function leftActive() {
            //$scope.leftStatus = 1;
            if ($scope.leftStatus == 0) {
                $scope.leftStatus = 1;
            } else {
                $scope.leftStatus = 0;
            }

        }

        var detailsSet;
        $scope.repeatFinish = function () {
            var aa = $('.sample_goal');
            for (var i = 0; i < aa.length; i++) {
                $(aa[i]).goalProgress({
                    goalAmount: 100,
                    currentAmount: $scope.collectDetail[i].v4,
                    textBefore: '',
                    textAfter: '%'
                })
            }
        };


        $scope.toggleLeft = function () {
            $ionicSideMenuDelegate.toggleLeft();
        };


        $scope.user = localStorageService.get('user');
        console.log($scope.user);
        $scope.playStatus = {
            sscStatus: 0,
            pkStatus: 0
        };
        $scope.statusReturn = statusReturn;
        $scope.openLink = openLink;
        $scope.loginout = loginout;


        $scope.printCollect = [];
        $scope.openBannerLink = openBannerLink;

        //$scope.goBuyRights1 = goBuyRights1;
        $scope.liesList = liesList;
        // $scope.runbar = runbar;
        $scope.$on('$ionicView.afterEnter', function () {
            $('.sample_goal').goalProgress({
                goalAmount: 100,
                currentAmount: 100,
                textBefore: '',
                textAfter: '%'
            })
        });
        init();
        function init() {
            if ($scope.user.status == 0) {
                $scope.play_id = 0;
            }
            if (localStorageService.get("detailsSet")) {
                detailsSet = localStorageService.get("detailsSet");
                //console.log(detailsSet);
            } else {
                detailsSet = {
                    code: 3,
                    num: 5
                }
            }
            $ionicTabsDelegate.showBar(true);//隐藏开奖走势导航栏
          //  banner();
            lottery();
          //  notice();
          //  pkScheme();
          //  myCollect();
          //  isShowRecharge();
            //获取新闻列表
          //  checkStatus();




            document.addEventListener("visibilitychange", onVisibilityChanged, false);
        }

        //是否显示充值按钮
        function isShowRecharge() {
            yikeTaishan.isShowRecharge()
                .then(function (data) {
                    if ($ionicPlatform.is("IOS")) {
                        $scope.is_open = data.result.open;
                    } else {
                        $scope.is_open = 1;
                    }
                    $scope.$digest();
                })
        }

        //
        function onVisibilityChanged() {
            lottery();
        }

        //权限不够退回
        function statusReturn() {
            $yikeUtils.toast('购买权限之后才能使用此功能');
        }


        //banner
        function banner() {
            yikeTaishan.banner()
                .then(function (banner) {
                    if (banner.status == 1) {
                        $scope.banners = banner.result.banner;
                        $scope.$digest();
                        var swiper = new Swiper('.swiper-container', {
                            pagination: '.swiper-pagination',
                            autoplay: 2000,
                            paginationClickable: true,
                            observer: true,//修改swiper自己或子元素时，自动初始化swiper
                            observeParents: true//修改swiper的父元素时，自动初始化swiper
                        });
                    }
                });
        }

        //公告列表
        function notice() {
            yikeTaishan.notice()
                .then(function (data) {
                    if (data.status == 1) {
                        var pattern1 = /&lt;/gim;
                        var pattern2 = /&gt;/gim;
                        var pattern3 = /&quot;/gim;
                        for (var i = 0; i < data.result.notice.length; i++) {
                            data.result.notice[i].content = data.result.notice[i].content.replace(pattern1, '<');
                            data.result.notice[i].content = data.result.notice[i].content.replace(pattern2, '>');
                            data.result.notice[i].content = data.result.notice[i].content.replace(pattern3, '"');
                            data.result.notice[i].content = $sce.trustAsHtml(data.result.notice[i].content);
                        }
                        $scope.noticeList = data.result.notice;
                        $scope.$digest();
                        jQuery(".txtMarquee-left").slide({
                            mainCell: ".bd ul",
                            autoPlay: true,
                            effect: "leftMarquee",
                            vis: 2,
                            interTime: 50
                        });
                    }
                })
        }

        //首页历史开奖
        function lottery() {
            yikeTaishan.lottery('index', '')
                .then(function (lottery) {
                    if (lottery.status == 1) {
                        $scope.pk = lottery.result.pk10;
                        $scope.thispk = Number($scope.pk.num) + 1;
                        $scope.pkTime = parseInt($scope.pk.difference_time);//倒计时总秒数量
                        if (moment().hour() >= 0 && moment().hour() <= 8) {
                            $scope.playStatus.pkStatus = 2;
                        } else {
                            if ($scope.pkTime > 0) {
                                $scope.playStatus.pkStatus = 1;
                            } else {
                                $scope.playStatus.pkStatus = 0;
                            }
                        }
                        pkTimer($scope.pkTime);
                        $scope.$digest();
                    }
                })
        }

        //pk倒计时
        var pkt = 5;

        function pkTimer(intDiff) {
            clearInterval(pksh);
            pksh = setInterval(function () {
                var day = 0,
                    hour = 0,
                    minute = 0,
                    second = 0;//时间默认值
                if (intDiff > 0) {
                    day = Math.floor(intDiff / (60 * 60 * 24));
                    hour = Math.floor(intDiff / (60 * 60)) - (day * 24);
                    minute = Math.floor(intDiff / 60) - (day * 24 * 60) - (hour * 60);
                    second = Math.floor(intDiff) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
                } else {
                    clearInterval(pksh);
                    if (intDiff == 0) {
                        lottery();
                    } else {
                        pkt--;
                        if (pkt == 0) {
                            lottery();
                            pkt = 5;
                        } else {
                            pkTimer(-1);
                        }
                    }
                }
                if (minute <= 9) minute = '0' + minute;
                if (second <= 9) second = '0' + second;
                $scope.pktime = minute + ':' + second;
                $scope.$digest();
                intDiff--;
            }, 1000);
        }

        //跳自定义链接
        function openBannerLink(link) {
            window.open(link, '_system');
        }

        //跳转官方网站
        function openLink() {
            window.open('http://www.taishanjihua.com', '_system');
        }

        function pkScheme() {
            yikeTaishan.pkScheme($scope.user.token)
                .then(function (data) {
                    $scope.allplans = data.result.plan;
                    //console.log($scope.allplans);
                    $ionicLoading.hide();
                })
        }

        //我的收藏
        function myCollect() {
            $ionicLoading.show({
                template: '<ion-spinner icon="bubbles"></ion-spinner>'
            });
            yikeTaishan.expire($scope.user.id, $scope.user.token)
                .then(function (data) {
                    //console.log(data);
                    if (data.status == 1) {
                        yikeTaishan.myCollect('my_collection', 'pk10', $scope.user.id)
                            .then(function (data) {
                                //console.log(data);
                                $ionicLoading.hide();

                                $scope.staus = data.status;

                                if (data.status == 1) {
                                    for (var i = 0, l = data.result.collection.length; i < l; i++) {
                                        data.result.collection[i].id_img = data.result.collection[i].plan_id - 1;
                                    }
                                    $scope.play_id = data.result.collection[0].plan_id;
                                    $scope.collect = data.result.collection;

                                    //console.log($scope.collect);
                                    //console.log($scope.collect[0].plan_id);
                                    liesList($scope.collect[0].plan_id);


                                    $scope.$digest();
                                    new Swiper(".swiper-container-plays", {
                                        direction: "horizontal",
                                        slidesPerView: 3,
                                        observer: true
                                        /*loop:true*/
                                    });
                                } else {
                                    $scope.collect = [];
                                    $yikeUtils.toast(data.result.collection);
                                }
                            })
                    } else {
                        clearInterval(pksh);
                        var alertPopup = $ionicPopup.alert({
                            title: '提示',
                            template: data.result.result,
                            buttons: [{
                                text: '确定',
                                type: 'button-positive'
                            }]
                        });
                        alertPopup.then(function () {
                            $ionicLoading.hide();
                            localStorageService.remove('user');
                            $state.go('login')
                        });
                    }
                })
        }

        /*假数据*/
        $scope.fadeList = [
            {
                plans: 0, list: [
                {name: "冠军定位", id: 1, type: "定码", play_id: 0},
                {name: "亚军定位", id: 2, type: "定码", play_id: 0},
                {name: "季军定位", id: 3, type: "定码", play_id: 0},
                {name: "第四名定位", id: 4, type: "定码", play_id: 0},
                {name: "第五名定位", id: 5, type: "定码", play_id: 0}
            ]
            },
            {
                plans: 1, list: [
                {name: "冠军定位", id: 1, type: "大小", play_id: 1},
                {name: "亚军定位", id: 2, type: "大小", play_id: 1},
                {name: "季军定位", id: 3, type: "大小", play_id: 1},
                {name: "第四名定位", id: 4, type: "大小", play_id: 1},
                {name: "第五名定位", id: 5, type: "大小", play_id: 1}
            ]
            },
            {
                plans: 2, list: [
                {name: "冠军定位", id: 1, type: "龙", play_id: 2},
                {name: "亚军定位", id: 2, type: "虎", play_id: 2},
                {name: "季军定位", id: 3, type: "虎", play_id: 2},
                {name: "第四名定位", id: 4, type: "龙", play_id: 2},
                {name: "第五名定位", id: 5, type: "虎", play_id: 2}
            ]
            }
        ];
        $scope.fadeListDetails = $scope.fadeList[0].list;


        //购买授权
        /*function goBuyRights1(){
         $rootScope.buytype = 1;
         $state.go('pay-rights');
         }*/

        /*获取系列下的详情*/
        $scope.collectDetail = [];
        //console.log($scope.collectDetail);

        function liesList(play_id) {
            console.log(play_id);
            //if($scope.user.status == "0"){
            //    $scope.play_id = play_id;
            //    $scope.fadeListDetails = $scope.fadeList[play_id].list;
            //
            //}else{
            $ionicLoading.show({
                template: '<ion-spinner icon="bubbles"></ion-spinner>'
            });
            $scope.collectDetail.length = 0;
            yikeTaishan.pkDetails(undefined, play_id, detailsSet.code, detailsSet.num)
                .then(function (data) {
                    //console.log(data);
                    $ionicLoading.hide();
                    $scope.play_id = play_id;
                    var detailTempArr = data.result.row.row;
                    $scope.rowId = data.result.row.id;
                    //console.log(detailTempArr);
                    for (var i = 0; i < detailTempArr.length; i++) {
                        var a = detailTempArr[i].win1.split(' ');
                        var c = {};
                        c.v1 = a[0];
                        c.v2 = a[1];
                        c.v3 = detailTempArr[i].win3;
                        c.v4 = detailTempArr[i].win.rate;
                        c.v5 = detailTempArr[i].plan.id;
                        c.v6 = detailTempArr[i].plan.type;
                        $scope.collectDetail.push(c);

                    }
                    //console.log($scope.collectDetail);
                    var checkbar = setInterval(function () {
                        if ($('.sample_goal').length == $scope.collectDetail.length) {
                            clearInterval(checkbar);
                        }
                        $scope.$$phase || $scope.$digest();
                    }, 1000);
                    $scope.$digest();
                });
            //}
        }



        //获取全部新闻列表
        function checkStatus(){
            yikeTaishan.newsLists('')
                .then(function (data) {
                    console.log(data);
                    $scope.newData = data.result.list;
                    console.log($scope.newData);
                    $scope.$digest();
                });
        }

        //获取其他新闻列表
        $scope.getNewLists = getNewLists;
        function getNewLists(type){
            $scope.activeStatu = type;
            yikeTaishan.newsLists(type)
                .then(function (data) {
                    console.log(data);
                    $scope.newData = data.result.list;
                    console.log($scope.newData);
                    $scope.$digest();
                });

        }





        //退出登录
        function loginout() {
            yikeTaishan.expire($scope.user.id, $scope.user.token)
                .then(function (data) {
                    if (data.status == 1) {
                        var comfirmPopup = $ionicPopup.confirm({
                            title: '退出登录',
                            template: '确认要退出登录？',
                            okText: '确定',
                            cancelText: '取消',
                            okType: "button-danger"
                        });
                        comfirmPopup.then(function (res) {
                            if (res) {
                                yikeTaishan.logout($scope.user.id)
                                    .then(function (data) {
                                        $yikeUtils.toast(data.result.result);
                                        if (data.status == 1) {
                                            localStorageService.remove('user');
                                            $state.go('login');
                                        }
                                    })
                            }
                        });
                    } else {
                        var alertPopup = $ionicPopup.alert({
                            title: '提示',
                            template: data.result.result,
                            buttons: [{
                                text: '确定',
                                type: 'button-positive'
                            }]
                        });
                        alertPopup.then(function () {
                            localStorageService.remove('user');
                            $state.go('login')
                        });
                    }
                })
        }


    }
})();
